package com.example.user.controller;

import com.example.common.Result;
import com.example.user.service.UserService;
import com.example.user_model.entity.User;
import com.example.utils.ValidateCodeUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author sjz
 * @since 2024-07-10
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //生成一个4位数随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code:{}", code);
            //调用阿里云的短信服务
            /*try {
                String[] args = {phone, code};
                SMSUtils.main(args);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }*/
            //优化:将验证码存入redis缓存当中,有效期设置为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return Result.success("手机验证码短信发送成功");
        }
        return Result.error("手机验证码发送失败");
    }

    /**
     * 校验登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody Map<String, String> map) {
        log.info(map.toString());
        //获取前端传过来的(页面上填写的手机号跟验证码)
        String phone = map.get("phone");
        String code = map.get("code");
        String token = userService.login(phone, code);
        if (token == null) {
            return Result.error("验证码错误,登录失败!");
        }
        Random rand = new Random();
        redisTemplate.opsForValue().set("Authorization", token, 30 + rand.nextInt(100), TimeUnit.MINUTES);
        return Result.success(token);
    }


    @PostMapping("/loginout")
    public Result<String> loginOut(HttpSession session) {
        log.info("退出登录");
        return Result.success("退出成功!");
    }

}
